package com.recipes.meg;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.speech.RecognizerIntent;

public class Menu extends Activity {
    // Declare variables to hold a sqlite database and database helper
	SQLiteDatabase db;
	DatabaseHelper db_helper;
	
	// Declare two constants to be used as request codes to search by name and by ing
    private static final int VOICE_SEARCH_BY_NAME = 0;
    private static final int VOICE_SEARCH_BY_ING = 1;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // Initialize database helper
        db_helper = new DatabaseHelper(this);
        
        // Initialize button to create a recipe
        Button create = (Button) findViewById(R.id.create);
        
        // Initialize button to search for a recipe
        Button search = (Button) findViewById(R.id.search);
        
        // Initialize button to list all recipes
        Button list = (Button) findViewById(R.id.list);

        // Initialize button to use speech to text to search by name
        Button voice_by_name = (Button) findViewById(R.id.voice_by_name);

        // Initialize button to use speech to text to search by name
        Button voice_by_ing = (Button) findViewById(R.id.voice_by_ing);
        
        // Create onClickListener for create button
        create.setOnClickListener(new View.OnClickListener() {
			// Override onClick function
			@Override
			public void onClick(View v) {
				// Start new intent to start create activity
				Intent start_create = new Intent(getApplicationContext(), Create.class);
				
				// Start create activity
				startActivity(start_create);
			}
		});
        
        // Set onClickListener for search button
        search.setOnClickListener(new View.OnClickListener() {
			// Override onClick function
			@Override
			public void onClick(View v) {
		        // Initialize EditText to give searchable name
		        EditText name_in = (EditText) findViewById(R.id.name_in);
		        
		        // Initialize EditText to give searchable ingredient
		        EditText ing_in = (EditText) findViewById(R.id.ing_in);
		        
		        // Get the text from name_in
		        String name = name_in.getText().toString();
		        
		        // Get the text from ing_in
		        String ing = ing_in.getText().toString();
		        
		        // Check if both parameters are blank
		        if(name.equalsIgnoreCase("") && ing.equalsIgnoreCase("")){
		        	// If so then give an error message and return prematurely
		        	Toast.makeText(getApplicationContext(), "Cannot search with blank parameters", Toast.LENGTH_SHORT).show();
		        	return;
		        }
		        
		        // Check if given name is not blank
		        if(!name.equalsIgnoreCase("")){
		        	// Open database for reading and writing
		        	db = db_helper.getWritableDatabase();

		        	// Call function to search for recipe with given name
		        	ArrayList<Integer> ids = db_helper.findByName(db, name);

		        	// Close the database
		        	db.close();

		        	// Check if any ids were returned
		        	if(ids.size() > 0){
		        		// If so then check if exactly 1 id was returned
		        		if(ids.size() == 1){
		        			// If so create intent to start view recipe activity
		        			Intent start_view = new Intent(getApplicationContext(), ViewRecipe.class);

		        			// Add the only id to start_view intent as an extra
		        			start_view.putExtra("id", ids.get(0));

		        			// Start the view recipe activity using start_view intent
		        			startActivity(start_view);

		        			// Return from this function after starting the next activity
		        			return;
		        		}

		        		// Else more than 1 recipe was found
		        		else{
		        			// If so create intent to start choose activity
		        			Intent start_choose = new Intent(getApplicationContext(), Choose.class);

		        			// Add ids array to start_choose intent as an extra
		        			start_choose.putIntegerArrayListExtra("ids", ids);

		        			// Start the choose activity
		        			startActivity(start_choose);

		        			// Return from this function after starting the next activity
		        			return;
		        		}
		        	}
		        }
		        
		        // Check if given ing is not blank
		        if(!ing.equalsIgnoreCase("")){
		        	// Open the database for reading and writing
		        	db = db_helper.getWritableDatabase();

		        	// Call function to search for recipe by ingredient
		        	ArrayList<Integer> ids = db_helper.findByIng(db, ing);

		        	// Close the database
		        	db.close();

		        	// Check if any ids were returned
		        	if(ids.size() > 0){
		        		// If so then check if exactly 1 id was returned
		        		if(ids.size() == 1){
		        			// If so create intent to start view recipe activity
		        			Intent start_view = new Intent(getApplicationContext(), ViewRecipe.class);

		        			// Add the only id to start_view intent as an extra
		        			start_view.putExtra("id", ids.get(0));

		        			// Start the view recipe activity using start_view intent
		        			startActivity(start_view);

		        			// Return from this function after starting the next activity
		        			return;
		        		}

		        		// Else more than 1 recipe was found
		        		else{
		        			// If so create intent to start choose activity
		        			Intent start_choose = new Intent(getApplicationContext(), Choose.class);

		        			// Add ids array to start_choose intent as an extra
		        			start_choose.putIntegerArrayListExtra("ids", ids);

		        			// Start the choose activity
		        			startActivity(start_choose);

		        			// Return from this function after starting the next activity
		        			return;
		        		}
		        	}
		        }
		        
		        // If recipe was not found yet give message saying recipe was not found
		        Toast.makeText(getApplicationContext(), "Could not find any recipes", Toast.LENGTH_SHORT).show();
			}
		});
        
        // Set onClickListener for voice_by_name button
        voice_by_name.setOnClickListener(new View.OnClickListener() {
			// Override onClick function
			@Override
			public void onClick(View v) {
				// Start intent to be used to start speach to text activity
				Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
				
				// Display an hint to the user about what he should say.
				intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say The Name You Would Like to Search For");

				// Given an hint to the recognizer about what the user is going to say
				intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
						RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);

				// Specify how many results you want to receive. The results will be sorted
				// where the first result is the one with higher confidence.
				intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);

				// Start speach to text activity using search by name code
				startActivityForResult(intent, VOICE_SEARCH_BY_NAME);
			}
		});
        
        // Set onClickListener for voice_by_ing button
        voice_by_ing.setOnClickListener(new View.OnClickListener() {
			// Override onClick function
			@Override
			public void onClick(View v) {
				// Start intent to be used to start speach to text activity
				Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

				// Display an hint to the user about what he should say.
				intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say The Ingredient You Would Like to Search For");

				// Given an hint to the recognizer about what the user is going to say
				intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
						RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);

				// Specify how many results you want to receive. The results will be sorted
				// where the first result is the one with higher confidence.
				intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);

				// Start speach to text activity using search by ing code
				startActivityForResult(intent, VOICE_SEARCH_BY_ING);
			}
		});
        
        // Set onClickListener for list button
        list.setOnClickListener(new View.OnClickListener() {
			// Override onClick function
			@Override
			public void onClick(View v) {
				// Create an empty array list of integers
				ArrayList<Integer> ids = new ArrayList<Integer>();
				
				// Open database for reading
				db = db_helper.getWritableDatabase();
				
				// Get the number of rows in the database
				int num_rows = db_helper.getNumRows(db);
				
				// Close the database
				db.close();
				
				// Iterate once for each row in the database
				for(int i = 1; i <= num_rows; i++){
					// Add this recipes id to ids
					ids.add(i);
				}
				
				// Initialize intent to start choose activity
				Intent start_choose = new Intent(getApplicationContext(), Choose.class);
				
				// Put ids into start_choose intent as an extra
				start_choose.putIntegerArrayListExtra("ids", ids);
				
				// Start choose activity with start_choose intent
				startActivity(start_choose);
			}
		});
    }
    
	/**
	 * Handle the results from the recognition activity.
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// Check if this was a search by name request and result is ok
		if (requestCode == VOICE_SEARCH_BY_NAME && resultCode == RESULT_OK) {
			// Fill the list view with the strings the recognizer thought it could have heard
			ArrayList<String> matches = data.getStringArrayListExtra(
					RecognizerIntent.EXTRA_RESULTS);

			// If so then initialize a result set
			ArrayList<Integer> ids = new ArrayList<Integer>();

			// Open database for reading
			db = db_helper.getWritableDatabase();

			// Iterate through result set
			for(int i = 0; i < matches.size(); i++){
				// Get temporary result set by searching for recipes with name using this
					// match as the search term
				ArrayList<Integer> temp = db_helper.findByName(db, matches.get(i));

				// Check if temp is not empty
				if(temp.size() != 0){
					// If so then make ids temp and break this loop
					ids = temp;
					break;
				}
			}

			// Close the database
			db.close();

			// Check if any ids were returned
			if(ids.size() > 0){
				// If so then check if exactly 1 id was returned
				if(ids.size() == 1){
					// If so create intent to start view recipe activity
					Intent start_view = new Intent(getApplicationContext(), ViewRecipe.class);

					// Add the only id to start_view intent as an extra
					start_view.putExtra("id", ids.get(0));

					// Start the view recipe activity using start_view intent
					startActivity(start_view);

					// Return from this function after starting the next activity
					return;
				}

				// Else more than 1 recipe was found
				else{
					// If so create intent to start choose activity
					Intent start_choose = new Intent(getApplicationContext(), Choose.class);

					// Add ids array to start_choose intent as an extra
					start_choose.putIntegerArrayListExtra("ids", ids);

					// Start the choose activity
					startActivity(start_choose);

					// Return from this function after starting the next activity
					return;
				}
			}
		}
		
		// Else check if this was a search by ingredient and result was ok
		if(requestCode == VOICE_SEARCH_BY_ING && resultCode == RESULT_OK){
			// Fill the list view with the strings the recognizer thought it could have heard
			ArrayList<String> matches = data.getStringArrayListExtra(
					RecognizerIntent.EXTRA_RESULTS);
			
			// If so then initialize a result set
			ArrayList<Integer> ids = new ArrayList<Integer>();
			
			// Open database for reading
			db = db_helper.getWritableDatabase();
			
			// Iterate through result set
			for(int i = 0; i < matches.size(); i++){
				// Get temporary result set by searching for recipes with name using this
					// match as the search term
				ArrayList<Integer> temp = db_helper.findByIng(db, matches.get(i));
				
				// Check if temp is not empty
				if(temp.size() != 0){
					// If so then make ids temp and break this loop
					ids = temp;
					break;
				}
			}
			
			// Close the database
			db.close();
			
        	// Check if any ids were returned
        	if(ids.size() > 0){
        		// If so then check if exactly 1 id was returned
        		if(ids.size() == 1){
        			// If so create intent to start view recipe activity
        			Intent start_view = new Intent(getApplicationContext(), ViewRecipe.class);

        			// Add the only id to start_view intent as an extra
        			start_view.putExtra("id", ids.get(0));

        			// Start the view recipe activity using start_view intent
        			startActivity(start_view);

        			// Return from this function after starting the next activity
        			return;
        		}

        		// Else more than 1 recipe was found
        		else{
        			// If so create intent to start choose activity
        			Intent start_choose = new Intent(getApplicationContext(), Choose.class);

        			// Add ids array to start_choose intent as an extra
        			start_choose.putIntegerArrayListExtra("ids", ids);

        			// Start the choose activity
        			startActivity(start_choose);

        			// Return from this function after starting the next activity
        			return;
        		}
        	}
		}

        // If recipe was not found yet give message saying recipe was not found
        Toast.makeText(getApplicationContext(), "Could not find recipe", Toast.LENGTH_SHORT).show();
		
        // Call super function
		super.onActivityResult(requestCode, resultCode, data);
	}
}